﻿using FastIOC.Attribute;
using FastIOC.Definition;
using FastUtil.Convert;
using FastUtil.Data;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace FastIOC.Entity
{
    public class MutiRegisterEntity
    {
        public List<RegisterEntity> RegisterEntityList { set; get; }
        public Type BaseType { set; get; }
        public MutiRegisterEntity(Assembly[] AssemblyList, Type BaseType, bool IsAttribute = false)
        {
            RegisterEntityList = new List<RegisterEntity>();
            this.BaseType = BaseType;
            foreach (Assembly assItem in AssemblyList)
            {
                List<Type> typelist = null;
                if (IsAttribute)
                {
                    typelist = StructConvert.ConvertArrayToList(assItem.GetTypes()).FindAll(a => a.GetCustomAttribute(BaseType, true) != null);
                }
                else
                {
                    typelist = StructConvert.ConvertArrayToList(assItem.GetTypes()).FindAll(a => CompareUtil.IsAssignableFrom(a, BaseType) && a != BaseType);
                }
                foreach (Type typeItem in typelist)
                {
                    RegisterEntity RE = new RegisterEntity(typeItem);
                    if (IsAttribute && BaseType == typeof(Service))
                    {
                        //Service注入，自动给多个实现赋值别名
                        Service service = (Service)RE.RealType.GetCustomAttribute(typeof(Service), true);
                        RE.AsImplementedInterfaces(service.RegistName);
                    }
                    RegisterEntityList.Add(RE);
                }
            }

        }

        public MutiRegisterEntity AsImplementedInterfaces()
        {
            foreach (RegisterEntity item in RegisterEntityList)
            {
                item.AsImplementedInterfaces();
            }
            return this;
        }

        public MutiRegisterEntity EnableIntercept()
        {
            foreach (RegisterEntity item in RegisterEntityList)
            {
                item.EnableIntercept();
            }
            return this;
        }

        public MutiRegisterEntity InterceptedBy<T>() where T : IFastIntercept
        {
            foreach (RegisterEntity item in RegisterEntityList)
            {
                item.InterceptedBy<T>();
            }
            return this;
        }

        public MutiRegisterEntity UseAttributeIntercept()
        {
            foreach (RegisterEntity item in RegisterEntityList)
            {
                item.UseAttributeIntercept();
            }
            return this;
        }
    }
}
